<?php
/**
 * Created by PhpStorm.
 * User: zhengmingwei
 * Date: 2019/10/22
 * Time: 9:34 下午
 */

namespace addons\official\controller\api;

use addons\official\model\OfficialBaseModel;
use addons\official\model\OfficialCategory;
use app\common\controller\Api;
use think\Cache;
use think\Lang;

/**
 * 基础类
 * @ApiInternal
 */
class BaseApi extends Api
{
    /**
     * 无需鉴权的方法,但需要登录
     * @var array
     */
    protected $noNeedRight = ['*'];

    protected $language = 2;

    /**
     * 允许频繁访问的接口（方法格式：小写）
     * @var array
     */
    protected $frequently = [];

    public function _initialize()
    {
        parent::_initialize();
        //检测配置项缓存
        $this->detectionConfig();
        //获取栏目数据
        $this->language = (int) input('param.uni_language')?(int) input('param.uni_language'):2;
        //检测栏目
        $this->getAll0fficiaCategory();
    }


    /**
     * @ApiInternal
     * 检测生成栏目配置项目文件
     */
    public function getAll0fficiaCategory()
    {
        //生成配置文件
        $official_tree_category_url = ADDON_PATH . 'official' . DS . 'controller' . DS . 'common' . DS . 'official_tree_category.php';
        if (!file_exists($official_tree_category_url)) {
            $official_category = (new OfficialCategory())
                ->with(['son'])
                ->where('pid', 0)
                ->field(['content', 'e_content'], true)
                ->where('deletetime', null)
                ->order('weigh', 'desc')
                ->select();
            $tree_category_all = [];
            foreach ($official_category as $item) {
                $ca = $item->toArray();
                if (($ca['status'] == 2) && !empty($ca['official_rule_id'])){
                    $ca['official_rule'] = db('official_rule')->where('id',$ca['official_rule_id'])->find();
                }
                if (!empty($ca['son'])){
                    foreach ($ca['son'] as $key => $val){
                        if (($val['status'] == 2) && !empty($val['official_rule_id'])){
                            $ca['son'][$key]['official_rule'] = db('official_rule')->where('id',$val['official_rule_id'])->find();
                        }
                    }
                }
                $tree_category_all[] = $ca;
            }
            file_put_contents(
                $official_tree_category_url,
                '<?php' . "\n\nreturn " . var_export_short($tree_category_all) . ";\n"
            );
        }
    }



    /**
     * 检测配置项缓存
     * @ApiInternal
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function detectionConfig(){
        $official_config_url = ADDON_PATH . 'official' . DS . 'controller' . DS . 'common' . DS . 'official_config.php';
        if (!file_exists($official_config_url)) {
            $config_all = [];
            $data = db('official_config')->select();
            foreach ($data as $item) {
                if ($item['type'] == 'image'){
                    $item['value'] = cdnurl($item['value'],true);
                }
                $config_all[$item['name']] = $item;
            }
            file_put_contents(
                $official_config_url,
                '<?php' . "\n\nreturn " . var_export_short($config_all) . ";\n"
            );
        }
    }



    /**
     * @ApiInternal
     * 查询父子级栏目以及某个子级栏目下的列表数据
     * @param $father_id 父级id
     * @param int $son_id 子级数量
     * @param int $son_num 子级id
     * @param int $data_num 列表数据数量
     */
    public function getFatherIsSon($father_id, $son_num = 10, $son_id = 0, $data_num = 8)
    {
        //查询父级
        $official_tree_category_url = ADDON_PATH . 'official' . DS . 'controller' . DS . 'common' . DS . 'official_tree_category.php';
        if (file_exists($official_tree_category_url)) {
            $tree_category_all = include $official_tree_category_url;
            foreach ($tree_category_all as $item) {
                if ($item['id'] == $father_id) {
                    $father = $item;
                }
            }
        }
        //截取几个子级栏目
        $father['son'] = array_slice($father['son'], 0, $son_num);
        //如果$son_id为0 默认查找第一个子集列表
        if ($son_id == 0) {
            foreach ($tree_category_all as $item) {
                if (isset($item['son']) && !empty($item['son'])) {
                    foreach ($item['son'] as $v) {
                        if (($v['pid'] == $father_id) && ($son_id == 0)) {
                            $son_id = $v['id'];
                        }
                    }
                }
            }
        }
        //查询数据
        $array = [];
        if ($data_num) {
            $model_name = "\addons\official\model\\" . (new OfficialBaseModel())->queryTableName($son_id);
            $data = (new $model_name)
                ->where('official_category_id', $son_id)
                ->where('language', $this->language)
                ->field(['content'], true)
                ->order('weigh', 'desc')
                ->limit($data_num)
                ->select();
            //3.编辑时间
            if (!empty($data)){
                foreach ($data as $key => $son) {
                    $son['createtime'] = date('Y-m-d',$son['createtime']);
                    $son['updatetime'] = date('Y-m-d',$son['updatetime']);
                    $array[] = $son;
                }
            }
        }
        //返回数据
        $father['data'] = $array;
        return $father;
    }


    /**
     * @ApiInternal
     * 查询某个栏目以及栏目下的列表数据
     * @param $c_id 栏目ID
     * @param int $data_num 数据条数
     */
    public function getOneCategoryIsData($c_id, $data_num = 8)
    {
        //1.查询父级
        $official_tree_category_url = ADDON_PATH . 'official' . DS . 'controller' . DS . 'common' . DS . 'official_tree_category.php';
        if (file_exists($official_tree_category_url)) {
            $tree_category_all = include $official_tree_category_url;
            foreach ($tree_category_all as $item) {
                foreach ($item['son'] as $son) {
                    if ($son['id'] == $c_id) {
                        $category = $son;
                    }
                }
                if ($item['id'] == $c_id) {
                    unset($item['son']);
                    $category = $item;
                }
            }
        }

        //2.查询数据
        $data = db((new OfficialBaseModel())->queryTableName($c_id))
            ->where('official_category_id', $c_id)
            ->where('language', $this->language)
            ->field(['content'], true)
            ->order('weigh', 'desc')
            ->limit($data_num)
            ->select();
        //3.编辑时间
        $array = [];
        if (!empty($data)){
            foreach ($data as $key => $son) {
                $son['createtime'] = date('Y-m-d',$son['createtime']);
                $son['updatetime'] = date('Y-m-d',$son['updatetime']);
                $array[] = $son;
            }
        }
        //4.返回数据
        $category['data'] = $array;
        return $category;
    }

}